﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;

namespace Common.DataAnnotations
{
    /// <summary>
    /// 集合大小验证
    /// </summary>
    public class ArrayValidationAttribute : ValidationAttribute
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="minLength">集合元素最小数量</param>
        public ArrayValidationAttribute(int minLength)
        {
            this.MinLength = minLength;
            this.MaxLength = int.MaxValue;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="minLength">集合元素最小数量</param>
        /// <param name="maxLength">集合元素最大数量</param>
        public ArrayValidationAttribute(int minLength, int maxLength)
        {
            this.MinLength = minLength;
            this.MaxLength = maxLength;
        }

        /// <summary>
        /// 最小长度
        /// </summary>
        public int MinLength { get; set; }

        /// <summary>
        /// 最大长度
        /// </summary>
        public int MaxLength { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public override bool IsValid(object value)
        {
            string[] sss = new string[] { };
            var temp = value as ICollection;
            if (temp?.Count < this.MinLength)
            {
                ErrorMessage = $"请设置{0}的选项，最少{this.MinLength}个选项！";
                return false;
            }
            if (temp.Count > this.MaxLength)
            {
                ErrorMessage = $"{0}选项已超出限制，最多可设置{this.MaxLength}个选项！";
                return false;
            }
            return true;
        }
    }
}
